import { defineStore } from "pinia";
import * as langs from './langs'
import { listApi as langListApi } from "@/api/system/Lang";
import { listApi as localeListApi } from "@/api/system/Locale";


type Locales = Array<{code : string, name : string}>


export const useI18nStore = defineStore<string, {storeKey : string, locale : string, langs : Array<{[key:string] : string}>, lang : {[key:string] : string}, locales:Locales}, {langOptions : () => {code:string, name:string}[]}, {setLocale : (locale:string) => void, t : (key:string, args?:Array<string|number>) => string, join :(key:string, str:string|number) => void, concat : (...key:Array<string|[string, string[]]>) => string, changeLang : () => void, init : () => Promise<void>}>('i18nStore', {
    state : () => ({
        storeKey : 'locale',
        langs : [],
        lang : {},
        locale : 'ZH',
        locales : []
    }),

    getters : {
        langOptions() {
            let options:{code:string, name:string}[] = []
            for(let k in this.lang) {
                options.push({code : k, name : this.lang[k]})
            }

            return options
        }
    },

    actions : {
        setLocale(locale:string) {
            this.locale = locale
            localStorage.setItem(this.storeKey, locale)
            this.changeLang()
        },

        changeLang() {console.log(this.locale)
            this.lang = {
                ...langs[this.locale].default
            }

            this.langs.forEach(item => {
                this.lang[item.code] = item.values[this.locale]
            })
        },

        t(key:string, args?:Array<string|number>) {
            let word:string = key.split('.').reduce((a, b) => a[b] || b, this.lang)
            if(args) {
                args.forEach(arg => {
                    word = word.replace('{}', arg as string)
                })
            }
    
            return word
        },

        concat(...keys:Array<string | [string, string[]]>) {
            let words:string[] = []
            keys.forEach(key => {
                if(typeof key == 'string') {
                    words.push(this.t(key))
                }else {
                    words.push(this.t(key[0], key[1]))
                }
            })
            
            return words.join(this.locale == 'ZH' ? '' : ' ')
        },

        join(...words:Array<string|number>) {
            return words.join(this.locale == 'ZH' ? '' : ' ')
        },

        async init() {
            this.changeLang()
        }

    }
})